// JavaScript Document
var PresidentsDataStore;
var PresidentsColumnModel;
var PresidentListingEditorGrid;
var PresidentListingWindow;
var EntitiesDefinition;
var Tree_Category_Loader;
var Tree_Category;
Ext.onReady(function(){
	Ext.QuickTips.init();
	Tree_Category_Loader = new Ext.tree.TreeLoader({
        dataUrl   :"server/EntitiesTree.php"
    });
	
    Tree_Category = new Ext.tree.TreePanel({
        collapsible      : false,
        animCollapse     : false,
        border           : true,
        id               : "tree_projectcategory",
        el               : "west",
        autoScroll       : true,
        animate          : true,
        enableDD         : true,
        containerScroll  : true,
		lines			 : false,
		border			 : false,
		titleCollapse 	 : true,
		useArrows		 : true,
		layout			 : 'fit',
        height           : 'auto',
        width            : 'auto',
		
        loader           : Tree_Category_Loader,
		tbar			 : 	[
								new Ext.Button({
									text: 'Create Entity',
									iconCls: 'btn-add',
									handler: function(){
										CreateEntity();
									}
								})
							]
    });
	var r = 0;
	
	Tree_Category.on('contextmenu', RenderEntityTreeMenu);
	Tree_Category.on('click', Softab.ClientProperties.LoadSource);
	Tree_Category.on('collapse',function(){
		alert("a");
	});
 	Tree_Category.on('click', function(node, event){
		Softab.GetEntityGrid(node, event)
	});
    // SET the root node.
    var Tree_Category_Root = new Ext.tree.AsyncTreeNode({
        text		: 'Entitati',
        draggable	: false,
		cls			:'feeds-node',
        id			: '0',				// this IS the id of the startnode
		expanded	:true
    });
	
	function AddNewEntityItem()
	{
		var rec = selectedRecord;
		//alert(selectedRecord.data.id);
		//alert(store.data.id);
		var win = new Ext.Window({
 			width: 'auto',
			id:'autoload-win',
			autoScroll:true,
			modal:true,
			autoWidth:true,
			autoHeight:true,
			height:550,
			onEsc:function(){this.close()},
			/*
			autoLoad:{
				url:'autoload-content.php'
			},
			*/
			title: 'Entity Name: None, <b>Record id</b>: ' + rec.data.id,
			listeners:{show:function(){
				this.loadMask = new Ext.LoadMask(this.body, {
					msg:'Loading. Please wait...'
				});
			}}
		});
		Ext.Ajax.request({
					url: 'server/EntityForm.php?__id='+entityId,
					success: function(response) {
						
						r = response.responseText;
						//alert(eval(r));
						formItems = eval(r);
						/*
						var gridDefinition = eval(r);
						gridColumns = eval(gridDefinition[0]);
						myData = eval(gridDefinition[1]);
						
						var storeDef = eval(gridDefinition[2]);
						*/
						
						var entityForm = new Ext.FormPanel({
							id				: 'myForm',
							standardSubmit	: false,
							title 			: 'TitluPanel',
							action			: 'server/EntitySave.php',
							width			: 'auto',
							autoScroll		: true,
							labelWidth		: 150,
							height			: 500,
							width			: 700,
							isUpload		: true,
							defaultType		: "textfield",
							items			: formItems,
							buttonAlign		: "center",
							buttons			:[
												new Ext.Button({
													text : 'Salveaza',
													
													handler: function() {
														entityForm.getForm().doAction('submit', {url:'server/EntitySave.php'})
														
//														entityForm.getForm().Action.Submit({
//															url:'server/EntitySave.php'
//															});
//														entityForm.getForm().getEl().dom.action = 'server/EntitySave.php';
//													    entityForm.getForm().getEl().dom.method = 'POST';
//														entityForm.getForm().getEl().dom.enctype = 'multipart/form-data';
//														entityForm.getForm().getEl().dom.target = 'hiddenIframe';
//												        entityForm.getForm().submit();
												    }
												    
												})
											]
						});
						
						win.add(entityForm);
				 		win.show();
					}
				});
	}
	
	function EditEntityItem(__id){
		var rec = selectedRecord;
	}
	
	function renderMenu(grid, rowIndex, e) {
			e.stopEvent();
			var coords = e.getXY();
			//alert();
			//OK, we have our record, now how do we pass
            //it to the referenced handler?
			selectedRecord = grid.getStore().getAt(rowIndex);
			
			var messageContextMenu = new Ext.menu.Menu({
				id: 'messageContextMenu',
				items: [
					{
						text: 'Properties',
						//handler: properties,
						scope: this
					},
					{
						text		: 'Editare inregistrare',
						scope		: this,
						handler: function(){
							EditEntityItem(selectedRecord);
						}
					},
//					{
//		                text: 'I like Ext',
//						//when checked has a boolean value,
//						//it is assumed to be a CheckItem
//		                checked: true  
//		                //checkHandler: onItemCheck
//		            },
					{
						text		: 'Adauge inregistrare',
						scope		: this,
						handler		: AddNewEntityItem
					}
				]
			});
			
			//predefine a menu item
			/*
			var menuItem = new Ext.menu.Item({
				text		: 'Adauge inregistrareOld',
				scope		: this,
				handler		: AddNewEntityItem(record)
			});
     		
			//shows how to add items dynamically
            var item = messageContextMenu.add(
				'-',
				menuItem, //add item by reference
				{	
					//handler: onMessageContextItemClick(this,['open']),
					//handler: function(){
	                //	this.viewer.openTab(this.ctxRecord);
	                //},
					iconCls: 'add',
					text: '<u>Insert above</u>',
					tooltip: 'Insert a row above this line'
				},
					{text: '<b>Print</b>', menu: new Ext.menu.Menu({// <-- submenu by nested config object
						items: [
							{text: 'PDF',  handler:function(){callPrintPreview("PDF");} },
							{text: 'EXCEL',handler:function(){callPrintPreview("EXCEL ");} },
							{text: 'HTML', handler:function(){callPrintPreview("HTML") ;} },
							{text: 'WORD', handler:function(){callPrintPreview("WORD") ;} }
						]
					})},
					{text: '<b>Save Preferences</b>',handler: function(){saveUserPref(Ext.encode(colModel.config));}}
			);
			*/
			messageContextMenu.showAt([coords[0], coords[1]]);
			e.preventDefault();//to disable the standard browser context menu
		}
		
	function renderEntityMenu(grid, rowIndex, e) {
			e.stopEvent();
			var coords = e.getXY();
			//alert();
			//OK, we have our record, now how do we pass
            //it to the referenced handler?
			//selectedRecord = grid.getStore().getAt(rowIndex);

			var messageContextMenu = new Ext.menu.Menu({
				id: 'messageContextMenu',
				items: [
					{
						text: 'Properties',
						//handler: properties,
						scope: this
					},
					{
						text		: 'Editare inregistrare',
						scope		: this,
						handler: function(){
							EditEntityItem(selectedRecord);
						}
					},
//					{
//		                text: 'I like Ext',
//						//when checked has a boolean value,
//						//it is assumed to be a CheckItem
//		                checked: true  
//		                //checkHandler: onItemCheck
//		            },
					{
						text		: 'Adauge inregistrare',
						scope		: this,
						handler		: AddNewEntityItem
					}
				]
			});
			messageContextMenu.showAt([coords[0], coords[1]]);
			e.preventDefault();//to disable the standard browser context menu
		}
    Tree_Category.setRootNode(Tree_Category_Root);
	
    Tree_Category.render();
    Tree_Category_Root.expand();
});

function RenderEntityTreeMenu(node, event){
	
	var coords = event.getXY();
	var treeContextMenu;
	var entityId;
	if (!node.isLeaf()){
		entityId = node.id;
	}else{
		entityId = node.parentNode.id;
	}
	var fieldTypesMenu = new Ext.menu.Menu({
		id : "fieldTypesMenu",
		items: 	[{
					text: 'Text Field',
					handler: function(){EntityFieldCreateForm("TextField", entityId)},
					scope: this
				},{
					text: 'Text Area',
					handler: function(){EntityFieldCreateForm("TextArea", entityId)},
					scope: this
				},{
					text: 'HTML Editor',
					handler: function(){EntityFieldCreateForm("HtmlEditor", entityId)},
					scope: this
				},{
					text: 'Time Field',
					handler: function(){EntityFieldCreateForm("TimeField", entityId)},
					scope: this
				},{
					text: 'Date Field',
					handler: function(){EntityFieldCreateForm("DateField", entityId)},
					scope: this
				},"-",{
					text: 'File on Disk',
					handler: function(){EntityFieldCreateForm("DiskFile", entityId)},
					scope: this
				},{
					text: 'File in DB',
					handler: function(){EntityFieldCreateForm("DBFile", entityId)},
					scope: this
				},{
					text: 'SS Lookup Field',
					handler: function(){EntityFieldCreateForm("SSLookupField", entityId)},
					scope: this
				},{
					text: 'MS Lookup Field',
					qtip: 'Multiple selection',
					handler: function(){EntityFieldCreateForm("MSLookupField", entityId)},
					scope: this
				}]
	});
	if (!node.isLeaf()) {
		 treeContextMenu = new Ext.menu.Menu({
			id: 'treeContextMenu',
			items: [{
				text: 'Proprietati',
				//handler: properties,
				scope: this
			}, {
				text: 'Editeaza entitatea',
				scope: this,
				handler: function(){
				//EditEntityItem(selectedRecord);
				}
			},
			"-",
			{
				text: 'Adaugare camp',
				scope: this,
				handler: function(){},
				menu : fieldTypesMenu
			}]
		});
	}else{
		treeContextMenu = new Ext.menu.Menu({
			id: 'treeContextMenu',
			items: [{
						text: 'Proprietati',
						//handler: properties,
						scope: this
					}, {
						text: 'Editeaza camp',
						scope: this,
						handler: function(){
						//EditEntityItem(selectedRecord);
						}
					}, 
					"-",
					{
						text: 'Adaugare camp',
						scope: this,
						handler: function(){},
						menu : fieldTypesMenu
			}]
		});
	}
	treeContextMenu.showAt([coords[0], coords[1]]);
	event.preventDefault()
	//messageContextMenu.show();
}

function saveThePresident(oGrid_event){
   Ext.Ajax.request({   
      waitMsg: 'Please wait...',
      url: 'server/database.php',
      params: {
         task: "UPDATEPRES",
         IDpresident: oGrid_event.record.data.IDpresident,
         FirstName: oGrid_event.record.data.FirstName,
         LastName: oGrid_event.record.data.LastName,
         PartyName: oGrid_event.record.data.PartyName,
         TookOffice: oGrid_event.record.data.TookOffice.format('Y-m-d'), // this time we'll format it thanks to ext
         LeftOffice: oGrid_event.record.data.LeftOffice.format('Y-m-d'),
         Income: oGrid_event.record.data.Income
      }, 
      success: function(response){							
         var result=eval(response.responseText);
         switch(result){
         case 1:
            PresidentsDataStore.commitChanges();   // changes successful, get rid of the red triangles
            PresidentsDataStore.reload({params: {start: 0, limit: 15}});          // reload our datastore.PresidentsDataStore.reload();

            break;					
         default:
            Ext.MessageBox.alert('Uh uh...','We couldn\'t save him...');
            break;
         }
      },
      failure: function(response){
         var result=response.responseText;
         Ext.MessageBox.alert('error','could not connect to the database. retry later');		
      }									    
   });   
  }
function CreateEntity(){
	var win = new Ext.Window({
		  width: 'auto',
		  id: 'CreateEntityWindow',
		  autoScroll: true,
		  modal: true,
		  height: 'auto',
		  width: 300,
		  onEsc: function(){
		      this.close()
		  },
		  title: 'Create entity',
		  iconCls: 'btn-add',
		  listeners: {
		      show: function(){
		          this.loadMask = new Ext.LoadMask(this.body, {
		              msg: 'Loading. Please wait...'
		          });
		      }
		  }
	});
	win.add(Softab.EntityCreateForm(win, Tree_Category));
	win.show();
}
var myData;
var grid;
var store;
var record;
var selectedRecord;
var entityId;